package com.sky.utils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;

@Data
@AllArgsConstructor
@Slf4j
public class MyAliUtils {
     private String endpoint;
     private String accessKeyId;
     private String accessKeySecret;
     private String bucketName;
    public  String upload(byte[] bytes,String objName){
        OSS ossClient= null;
     try {
         // 创建OSSClient实例。
          ossClient= new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
         // 创建PutObject请求。

         ossClient.putObject(bucketName, objName, new ByteArrayInputStream(bytes));
         //文件访问路径规则 https://BucketName.Endpoint/ObjectName
         StringBuilder stringBuilder = new StringBuilder("https://");
         stringBuilder
                 .append(bucketName)
                 .append(".")
                 .append(endpoint)
                 .append("/")
                 .append(objName);
         log.info("文件上传到:{}", stringBuilder.toString());
         return stringBuilder.toString();
     }catch (Exception e){
       log.info("上传失败",e);
       return null;
     }finally {
         if(ossClient!=null){
//             关闭客户端释放资源
             ossClient.shutdown();
         }
     }
    }
}
